package com.example.ddz.framework;

/**
 * Created by IntelliJ IDEA.
 * User: Marcel Melzig
 * Date: 26.07.11
 * Time: 19:11
 */

import java.util.ArrayList;
import java.util.List;

/**
 * This class handles the pooling. This concept is used because of the garbage collector. Instead of creating new objects
 * all of the time and keep the garbage collector working entirely, this class defines a number of processes the Handler
 * of this Framework can use.
 */
public class Pooling<T>
{
    /**
     * This interface could be used to generate a factory to create objects of any kind.
     *
     * @param <T> A generic type.
     */
    public interface PoolObjectFactory<T>
    {
        public T createObject();
    }

    private final List<T> freeObjects;
    private final PoolObjectFactory<T> factory;
    private final int maxSize;

    /**
     * Creates an instance of the Pooling class.
     *
     * @param factory A factory used to create objects of any type.
     * @param maxSize The maximum number of objects the pool can store.
     */
    public Pooling(PoolObjectFactory<T> factory, int maxSize)
    {
        this.factory = factory;
        this.maxSize = maxSize;
        this.freeObjects = new ArrayList<T>(maxSize);
    }

    /**
     * Returns an new object or one of the pool.
     *
     * @return An object of the pools type.
     */
    public T NewObject()
    {
        T object;
        if (freeObjects.size() == 0)
            object = factory.createObject();
        else
            object = freeObjects.remove(freeObjects.size() - 1);
        return object;
    }

    /**
     * Returns an given object back to the pool.
     *
     * @param object A generic type.
     */
    public void Free(T object)
    {
        if (freeObjects.size() < maxSize)
            freeObjects.add(object);
    }
}
